/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.krossk.servlets;

import br.com.krossk.dao.AreaDAO;
import br.com.krossk.dao.PrivilegioDAO;
import br.com.krossk.dao.SegmentoDAO;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.krossk.dao.UsuarioDAO;
import br.com.krossk.jpa.JPAFactory;
import br.com.krossk.jspControllers.Menu;
import br.com.krossk.model.Privilegio;
import br.com.krossk.model.Usuario;
import javax.servlet.RequestDispatcher;
import br.com.krossk.model.Area;
import br.com.krossk.model.Segmento;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpSession;
//import br.com.krossk.model.Privilegio;
/**
 *
 * @author user1
 */
public class IncluirUsuario extends HttpServlet {
   String caminho;
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String nomeUsuario = request.getParameter("nomeUsuario");
    String apelido = request.getParameter("apelido");
    String senha1 = request.getParameter("senha1");
    String senha2 = request.getParameter("senha2");
    String email = request.getParameter("email");
    String mensagem = null;
    if (senha1.equals(senha2)){

        List <Usuario> usuarios= UsuarioDAO.getInstance().getAll();
        boolean valido = false ;

        for(Usuario u:usuarios){
            if(u.getNickname().equals(apelido)) {valido = true; mensagem = "Já consta usuario com esse apelido, escolha outro!!";}
            if(u.getEmail().equals(email)) {valido = true; mensagem = "Consta cadastro desse email, cadastro não efetuado!!";}
            
        }

        if(valido == false){



            List<Area> areas = new ArrayList<Area>();
            int i=AreaDAO.getInstance().getAll().size();
            for(int n=1;n<=i;n++){
                try{
                    areas.add(AreaDAO.getInstance().getById(Integer.parseInt(request.getParameter("area"+n))));
                }catch(Exception ex){
                }
            }


            List<Segmento> segmentos = new ArrayList<Segmento>();
            i=SegmentoDAO.getInstance().getAll().size();
            for(int n=1;n<i;n++){
                try {
                    segmentos.add(SegmentoDAO.getInstance().getById(Integer.parseInt(request.getParameter("segmento"+n))));
                }catch (Exception ex){}
            }

            Usuario usuario = new Usuario(apelido, nomeUsuario, email, senha1);
            Privilegio p = PrivilegioDAO.getInstance().getById(3);
            usuario.setPrivilegio(p);
            usuario.setAreaCollection(areas);
            usuario.setSegmentoCollection(segmentos);

            EntityManager em = JPAFactory.getEntityManager();
            em.getTransaction().begin();
            em.persist(usuario);
            em.getTransaction().commit();
            em.close();
            HttpSession session = request.getSession();
            session.setAttribute("usuario", usuario);
            response.sendRedirect(Menu.HOME);
        }// fim do if usuario == null
        else{

             caminho = "pages/usuario/cadastro.jsp";
             doDispatcher(request, mensagem, response);

        } //fim do else


    }// fim do if senha1.equals(senha2)
       //  PrintWriter out = response.getWriter();
    else{
        caminho = "pages/usuario/cadastro.jsp";
        mensagem = "Você digitou duas senhas diferentes, refaça o cadastro !!";
        doDispatcher(request, mensagem, response);

    }
}

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

protected void doDispatcher(HttpServletRequest request, String msg, HttpServletResponse response) throws IOException, ServletException {
RequestDispatcher rd = request.getRequestDispatcher(caminho);
request.setAttribute("mensagem", msg);
rd.forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
